<template>
  <div class="app-container">
    <!-- 删除密码验证弹窗 -->
    <el-dialog
      title="安全验证"
      :visible.sync="deletePasswordDialog"
      width="400px"
      append-to-body
      custom-class="custom-dialog-position"
    >
      <el-form>
        <el-form-item label="管理员密码">
          <el-input
            v-model="deletePassword"
            type="password"
            placeholder="请输入管理员密码"
            show-password
            @keyup.enter.native="confirmDelete"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="deleteLoading"
          type="primary"
          @click="confirmDelete"
        >确 定
        </el-button>
        <el-button
          :disabled="deleteLoading"
          @click="deletePasswordDialog = false"
        >取 消
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配医生" :visible.sync="allocationOpen" width="500px" append-to-body
               custom-class="custom-dialog-position"
    >
      <el-form>
        <el-form-item label="选择医生" prop="doctor">
          <el-select
            v-model="selectedDoctorId"
            placeholder="请选择医生"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              label="<-暂不分配->"
              :value="-1"
            />
            <el-option
              v-for="item in doctorList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllocation">确 定</el-button>
        <el-button @click="allocationOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量分配弹窗 -->
    <el-dialog title="批量分配医生" :visible.sync="batchAllocationOpen" width="500px" append-to-body
               custom-class="custom-dialog-position"
    >
      <el-form>
        <el-form-item label="选择医生" prop="doctor">
          <el-select
            v-model="selectedBatchDoctorId"
            placeholder="请选择医生"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              label="<-暂不分配->"
              :value="-1"
            />
            <el-option
              v-for="item in doctorList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchAllocation">确 定</el-button>
        <el-button @click="batchAllocationOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="病患姓名" prop="childName">
        <el-input
          v-model="queryParams.childName"
          placeholder="请输入病患姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病患性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入病患性别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生姓名" prop="doctor">
        <el-input
          v-model="queryParams.doctor"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dcp:patient:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-user"
          size="mini"
          :disabled="multiple"
          @click="handleBatchAllocation"
          v-hasPermi="['dcp:patient:allocation']"
        >批量分配
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dcp:patient:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dcp:patient:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="patientId"/>
      <el-table-column label="病患名称" align="center" prop="childName"/>
      <el-table-column label="性别" align="center" prop="gender"/>
      <el-table-column label="年龄" align="center" prop="age"/>
      <el-table-column label="生日" align="center" prop="birth" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birth, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年级" align="center" prop="grade"/>
      <el-table-column label="所属医生" align="center" prop="doctor">
        <template slot-scope="scope">
    <span :style="{ color: scope.row.doctor ? '' : '#F56C6C' }">
      {{ scope.row.doctor || '未分配' }}
    </span>
        </template>
      </el-table-column>
      <el-table-column label="所用量表" align="center">
        <template slot-scope="scope">
          <el-tooltip
            :content="scope.row.scale ? scope.row.scale.replace(/◆/g, '\n') : '-'"
            effect="light"
            placement="top"
            :disabled="!scope.row.scale"
          >
            <div class="scale-content">
              {{ scope.row.scale ? scope.row.scale.replace(/◆/g, ' ') : '-' }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="量表完成情况" align="center">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.status ? '#67C23A' : '#F56C6C' }">
            {{ scope.row.status ? '已完成' : '未完成' }}
          </span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="住院号" align="center" prop="admissionNumber"/>-->
      <!--      <el-table-column label="就诊卡号" align="center" prop="cardNumber"/>-->
      <!--      <el-table-column label="民族" align="center" prop="ethnicity" />-->
      <!--      <el-table-column label="父亲职业" align="center" prop="fatherOccupation" />-->
      <!--      <el-table-column label="母亲职业" align="center" prop="motherOccupation" />-->
      <!--      <el-table-column label="门诊号" align="center" prop="patientNumber" />-->
      <!--      <el-table-column label="联系方式" align="center" prop="phonenumber" />-->
      <!--      <el-table-column label="家庭住址" align="center" prop="address" />-->
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAllocation(scope.row)"
            v-hasPermi="['dcp:patient:allocation']"
          >分配
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dcp:patient:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dcp:patient:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改病患管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="病患名称" prop="childName">
          <el-input v-model="form.childName" placeholder="请输入病患名称"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birth">
          <el-date-picker clearable
                          v-model="form.birth"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择生日"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入年级"/>
        </el-form-item>
        <el-form-item label="住院号" prop="admissionNumber">
          <el-input v-model="form.admissionNumber" placeholder="请输入住院号"/>
        </el-form-item>
        <el-form-item label="就诊卡号" prop="cardNumber">
          <el-input v-model="form.cardNumber" placeholder="请输入就诊卡号"/>
        </el-form-item>
        <!-- 分配量表-->
        <el-form-item label="分配量表" prop="assignedScaleId">
          <el-select v-model="assignedScaleIds" multiple placeholder="请选择量表" clearable>
            <el-option
              v-for="item in listScale"
              :key="item.scaleId"
              :label="item.scaleName"
              :value="item.scaleId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="民族" prop="ethnicity">
          <el-input v-model="form.ethnicity" placeholder="请输入民族"/>
        </el-form-item>
        <el-form-item label="父亲职业" prop="fatherOccupation">
          <el-input v-model="form.fatherOccupation" placeholder="请输入父亲职业"/>
        </el-form-item>
        <el-form-item label="母亲职业" prop="motherOccupation">
          <el-input v-model="form.motherOccupation" placeholder="请输入母亲职业"/>
        </el-form-item>
        <el-form-item label="门诊号" prop="patientNumber">
          <el-input v-model="form.patientNumber" placeholder="请输入门诊号"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="form.address" placeholder="请输入家庭住址"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPatient,
  getPatient,
  delPatient,
  addPatient,
  updatePatient,
  updateDoctor,
  addScaleScreen,
  updateDoctorList
} from '@/api/dcp/patient'
import { listDoctor, getPassWord } from '@/api/dcp/doctor'
import { listScale } from '@/api/dcp/scale'

export default {
  name: 'Patient',
  data() {
    return {
      listScale: [],
      assignedScaleIds: [],
      // 新增删除相关状态
      deletePasswordDialog: false,    // 密码弹窗显示状态
      deletePassword: '',             // 输入的密码
      pendingDeleteIds: [],           // 待删除的ID集合
      deleteLoading: false,            // 删除加载状态

      scaleList: [],
      // 新增批量分配相关状态
      batchAllocationOpen: false, // 批量分配弹窗
      selectedBatchDoctorId: null, // 批量分配的医生ID
      selectedPatientIds: [],      // 选中的病患ID数组
      // 新增数据项
      allocationOpen: false,      // 分配弹窗显示状态
      selectedDoctorId: null,     // 选中的医生ID
      currentPatientId: null,     // 当前操作的病患ID

      doctorList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 病患管理表格数据
      patientList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        childName: null,
        gender: null,
        birth: null,
        grade: null,
        doctor: null,
        admissionNumber: null,
        cardNumber: null,
        ethnicity: null,
        fatherOccupation: null,
        motherOccupation: null,
        patientNumber: null,
        phonenumber: null,
        address: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getScale()
    this.getList()
  },
  methods: {

    async getScale() {
      try {
        console.log('aaaaaaaaaaaaaaaaaaaa')
        const res = await listScale({ query: this.queryParams }) // 等待异步操作完成
        // console.log(res.rows); // 打印解析后的数据
        console.log('aaaaaaaaaaaaaaaaaaaa')
        this.listScale = res.rows
        console.log(this.listScale)
      } catch (error) {
        console.error('Error fetching data:', error)
      }
    },

    // 批量分配按钮点击事件
    handleBatchAllocation() {
      if (this.ids.length === 0) {
        this.$message.warning('请先选择要分配的病患')
        return
      }
      this.selectedPatientIds = this.ids // 存储选中的病患ID
      this.batchAllocationOpen = true    // 打开批量分配弹窗
      this.getDoctorList()               // 加载医生列表
    },

    // 批量分配提交

    handleAllocation(row) {
      this.getDoctorList()
      this.currentPatientId = row.patientId
      this.selectedDoctorId = null
      this.allocationOpen = true
      // 如果医生列表未加载则请求数据
      if (!this.doctorList || this.doctorList.length === 0) {
        this.getDoctorList()
      }
    },

    submitAllocation() {
      // 移除对selectedDoctorId的校验
      let params = {
        userId: this.selectedDoctorId, // 允许null值
        patientId: this.currentPatientId
      }

      updateDoctor(params).then(res => {
        this.allocationOpen = false
        this.getList()
        // 根据是否选择医生显示不同提示
        this.$message.success(this.selectedDoctorId ? '分配成功' : '已取消分配')
      }).catch(error => {
        this.$message.error('操作失败：' + error.message)
      })
    },

    submitBatchAllocation() {
      // 移除对selectedBatchDoctorId的非空校验
      if (this.selectedPatientIds.length === 0) {
        this.$message.warning('请选择患者')
        return
      }

      const requests = this.selectedPatientIds.map(patientId => {
        return updateDoctor({
          userId: this.selectedBatchDoctorId, // 允许null值
          patientId: patientId
        })
      })

      Promise.all(requests)
        .then(() => {
          const msg = this.selectedBatchDoctorId ?
            `成功分配 ${this.selectedPatientIds.length} 名患者` :
            `已移除 ${this.selectedPatientIds.length} 名患者的医生`
          this.$message.success(msg)
          this.batchAllocationOpen = false
          this.getList()
        })
        .catch(error => {
          this.$message.error('操作失败：' + (error.message || '请联系管理员'))
        })
    },
    /** 查询医生信息列表 */
    getDoctorList() {
      listDoctor(this.queryParams).then(response => {
        this.doctorList = response.rows
      })
    },
    /** 查询病患管理列表 */
    getList() {
      this.loading = true
      listPatient(this.queryParams).then(response => {
        this.patientList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        patientId: null,
        childName: null,
        gender: null,
        birth: null,
        grade: null,
        userId: null,
        admissionNumber: null,
        cardNumber: null,
        ethnicity: null,
        fatherOccupation: null,
        motherOccupation: null,
        patientNumber: null,
        phonenumber: null,
        address: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
      // this.getDoctorList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.patientId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getDoctorList()
      this.open = true
      this.title = '添加病患管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getScale()
      this.getDoctorList()
      const patientId = row.patientId || this.ids
      getPatient(patientId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改病患管理'
      })
    },
    addScaleScreen(data) {
      return addScaleScreen(data).catch(error => {
        this.$message.error('量表分配失败: ' + error.message)
        throw error // 保持错误传递
      })
    },
    /** 提交按钮 */
    submitForm() {
      // console.log(this.assignedScaleIds)

      console.log(this.form)
      let arr = []
      // 遍历所有选择的量表ID
      for (let i = 0; i < this.assignedScaleIds.length; i++) {
        // 在量表列表中查找匹配项
        const scale = this.listScale.find(
          item => item.scaleId === this.assignedScaleIds[i]
        )

        let params = {
          scaleId: this.assignedScaleIds[i],
          scaleName: scale ? scale.scaleName : '未知量表',
          patientId: this.form.patientId,
          patientName: this.form.childName,
          status: 0
        }
        arr.push(params)
      }
      console.log(arr)
      this.addScaleScreen(arr).then(res => {
      })
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.patientId != null) {
            updatePatient(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addPatient(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /*删除按钮操作 */
    handleDelete(row) {
      // 收集待删除ID（支持单条/批量）
      this.pendingDeleteIds = row.patientId ? [row.patientId] : this.ids

      if (this.pendingDeleteIds.length === 0) {
        this.$message.warning('请先选择要删除的项目')
        return
      }

      // 初始化删除状态
      this.deletePassword = ''
      this.deletePasswordDialog = true
    },

// 修改后的confirmDelete方法
    async confirmDelete() {
      try {

        this.deleteLoading = true

        // 调用接口并获取完整响应
        const response = await getPassWord({
          password: this.deletePassword
        })

        // 调试输出完整响应结构
        console.log('完整响应:', response)

        // 提取code字段（根据实际响应结构调整）
        const resultCode = response.data?.code || response.data

        if (resultCode !== 1) {
          this.$message.error('密码验证失败')
          return
        }

        // 3. 执行删除操作
        await delPatient(this.pendingDeleteIds)

        // 4. 处理成功状态
        this.$message.success('删除成功')
        this.deletePasswordDialog = false
        this.getList()
      } catch (error) {
        this.$message.error(`操作失败：${error.message}`)
      } finally {
        this.deleteLoading = false
      }
    }
  }
}
</script>
<style>

.custom-dialog-position.el-dialog {
  top: 30vh !important; /* 更大幅度下移 */
  transform: none !important; /* 清除默认位移 */
}

/* 统一行高 */
.scale-content {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 控制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 60px; /* 行高×行数 */
  line-height: 20px;
  text-align: left;
  white-space: normal !important;
}

/* 优化tooltip换行 */
.el-tooltip__popper {
  white-space: pre-line;
  max-width: 400px;
}
</style>
